#!/usr/bin/env python3
"""
网络调试助手二进制打包入口文件
"""
import os
import sys
import signal
import threading
import time
from pathlib import Path

def setup_paths():
    """设置路径和环境"""
    # 获取可执行文件所在目录
    if getattr(sys, 'frozen', False):
        # PyInstaller打包后的路径
        base_path = Path(sys.executable).parent
        # 在PyInstaller中，需要将_internal目录添加到Python路径
        internal_path = base_path / "_internal"
        sys.path.insert(0, str(internal_path))
    else:
        # 开发环境路径
        base_path = Path(__file__).parent
        sys.path.insert(0, str(base_path))
    
    # 设置工作目录
    os.chdir(base_path)
    
    return base_path

def handle_signal(signum, frame):
    """处理信号"""
    print(f"\n收到信号 {signum}，正在关闭服务...")
    sys.exit(0)

def main():
    """主函数"""
    # 设置路径
    base_path = setup_paths()
    print(f"应用路径: {base_path}")
    
    # 注册信号处理
    signal.signal(signal.SIGTERM, handle_signal)
    signal.signal(signal.SIGINT, handle_signal)
    
    # 导入应用模块
    try:
        from config import settings
        from main import app
        import uvicorn
        
        print(f"🚀 启动网络调试助手服务")
        print(f"📍 监听地址: {settings.HOST}:{settings.PORT}")
        print(f"🌐 Web界面: http://localhost:{settings.PORT}")
        print(f"📚 API文档: http://localhost:{settings.PORT}/docs")
        
        # 启动服务
        uvicorn.run(
            app,
            host=settings.HOST,
            port=settings.PORT,
            access_log=False,
            log_level="info"
        )
        
    except ImportError as e:
        print(f"❌ 导入模块失败: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()